package whf.framework.ext.helper;

import java.util.Iterator;
import java.util.List;

import whf.framework.ext.entity.MenuItem;
import whf.framework.security.UserContext;
import whf.framework.util.PermissionUtils;
import whf.framework.util.StringUtils;
import whf.framework.util.Utils;

/**
 * @author king
 *
 */
public class MenuItemHelper {
	private List<MenuItem> rootMenuItems = Utils.newArrayList();
	
	private List<MenuItem> menuItems = Utils.newArrayList();
	
	private UserContext userContext;
	
	public MenuItemHelper(UserContext userContext, List<MenuItem> menuItems) {
		this.menuItems = menuItems;
		for(Iterator<MenuItem> it = this.menuItems.iterator(); it.hasNext(); ) {
			MenuItem mi = (MenuItem)it.next();
			if(mi.getParent() == null) {
				this.rootMenuItems.add(mi);
				it.remove();
			}
		}
		this.buildRootMenuItems();
	}
	
	public MenuItemHelper(UserContext userContext, List<MenuItem> rootMenuItems, List<MenuItem> menuItems) {
		this.rootMenuItems = rootMenuItems;
		this.menuItems = menuItems;
		this.buildRootMenuItems();
	}
	
	private boolean hasPermission(MenuItem menuItem){
		if(this.userContext != null) {
			return PermissionUtils.hasPermission(userContext, menuItem);
		} else {
			return true;
		}
	}
	
	private void buildRootMenuItems(){
		for(MenuItem root: this.rootMenuItems) {
			if(!this.hasPermission(root)) 
				continue;
			this.buildMenuItem(root);
		}
		for(Iterator<MenuItem> it = this.rootMenuItems.iterator(); it.hasNext(); ) {
			MenuItem menuItem = (MenuItem)it.next();
			boolean clean = this.clean(menuItem);
			if(!clean) it.remove();
		}
	}
	
	/**
	 * 使用递归将所有子菜单加入
	 * @param parent
	 */
	private void buildMenuItem(MenuItem parent){
		for(Iterator<MenuItem> it = this.menuItems.iterator(); it.hasNext(); ) {
			MenuItem mi = (MenuItem)it.next();
			if(parent.idEquals(mi.getParent())) {
				if(!this.hasPermission(mi)) continue;
				parent.getChildren().add(mi);
				buildMenuItem(mi);
			}
		}
	}
	
	/**
	 * 清除无用的节点
	 * @param parent
	 */
	private boolean clean(MenuItem parent) {
		List<MenuItem> children = parent.getChildren();
		for(Iterator<MenuItem> it = children.iterator(); it.hasNext(); ) {
			MenuItem menuItem = (MenuItem)it.next();
			boolean clean = this.clean(menuItem);
			if(!clean) it.remove();
		}
		if(parent.getChildren().isEmpty() && StringUtils.isEmpty(parent.getHref())) 
			return false;
		else
			return true;
	}
	
	public List<MenuItem> getRootMenuItems() {
		return this.rootMenuItems;
	}
}
